<?php

namespace App\Models\Shop;

use App\Libraries\Tools\Constants;
use App\Libraries\Tools\ConstVar;
use App\Models\BaseModel;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class Shop extends BaseModel
{


    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'title',
        'status',
        'verify_status',
        'open_at',
        'close_at',
        'cover',
        'images',
        'consumption',
        'phone',
        'cell_phone',
        'province_id',
        'city_id',
        'district_id',
        'address',
    ];

    /**
     * The attributes excluded from the model's JSON form.
     *
     * @var array
     */
    protected $hidden = [
        'created_at','updated_at'
    ];

    protected $primaryKey = 'shop_id';
    protected $dateFormat = 'U';

    /**
     * 获取商家列表
     * @param Request $request
     * @param $cur_user_id
     * @return mixed
     */
    public function shops(Request $request, $cur_user_id){
        $lng = floatval($request['lng']);
        $lat = floatval($request['lat']);
        $user_lng = floatval($request['user_lng']);
        $user_lat = floatval($request['user_lat']);
        $lng_radius = floatval($request['lng_radius']);
        $lat_radius = floatval($request['lat_radius']);

        $where = '';
        $having = '';
        $order = '';
        $join = '';
        if(!empty($request['keyword']) || $request['keyword'] === '0'){
            $where .= " AND INSTR(s.title, '".$request['keyword']."') ";
        }
        if(!empty($request['district_id'])){
            $where .= " AND s.district_id={$request['district_id']} ";
        }
        if(!empty($request['city_id'])){
            $where .= " AND s.city_id={$request['city_id']} ";
        }
        if(!empty($request['type']) && $request['type'] != 12){
            $where .= " AND s.type='{$request['type']}' ";
        }elseif($request['type'] == 12){
            $where .= " AND s.type IN (6, 7, 9, 11, 12) ";
        }
        if(!empty($request['user_city_id'])){
            $priority = Shop::select('shop_id')->where('city_id', $request['user_city_id'])
                ->whereIn('priority', [2,3])
                ->get()
                ->toArray();
            if(!empty($priority)){
                $tmp = [];
                foreach($priority as $v){
                    $tmp[] = $v['shop_id'];
                }
                $priority = implode(',', $tmp);
                $where .= " OR s.shop_id IN ({$priority}) ";
            }
        }
        if(!empty($request['distance'])){
            $having = " HAVING distance <= {$request['distance']} ";
            if(!empty($priority)){
                $having .= " OR s.shop_id IN ({$priority}) ";
            }
        }
        switch($request['order']){//1-距离 2-评价 3-价格 4-智能 5-人气
            case 2:
                $order .= ' ,ss.score DESC, ss.comment DESC, distance ';
                break;
            case 3:
                $order .= ' ,s.consumption, distance ';
                break;
            case 4:
                $order .= ' ,distance,ss.score DESC,ss.view DESC ';
                break;
            case 5:
                $order .= ' ,ss.view DESC, distance ';
                break;
            default:
                $order .= ' ,distance ';
        }
        if(empty($request['district_id']) && empty($request['city_id'])
            && empty($request['fav']) && empty($request['keyword']) && !isset($request['type'])
            && empty($request['distance'])
        ){
            $up_left_lng = $lng+$lng_radius;
            $up_left_lat = $lat-$lat_radius;
            $up_right_lng = $lng+$lng_radius;
            $up_right_lat = $lat+$lat_radius;
            $down_right_lng = $lng-$lng_radius;
            $down_right_lat = $lat+$lat_radius;
            $down_left_lng = $lng-$lng_radius;
            $down_left_lat = $lat-$lat_radius;
            $having = " HAVING MBRContains(st_GeomFromText('POLYGON(($up_left_lng $up_left_lat,$up_right_lng $up_right_lat,$down_right_lng $down_right_lat,$down_left_lng $down_left_lat,$up_left_lng $up_left_lat))'), POINT(s.longitude, s.latitude)) ";
            if(!empty($priority)){
                $having .= " OR s.shop_id IN ({$priority}) ";
            }
        }

        if(!empty($request['fav'])){
            $join .= " RIGHT JOIN shop_fav sf ON sf.shop_id=s.shop_id AND sf.status=1 AND sf.user_id='{$cur_user_id}' ";
        }

        $distance_const = Constants::$DISTANCE_CONST;
        $start = ($request['page']-1) * $request['size'];
        $size = $request['size']+1;
        $data = [];
        $data['list'] = DB::select("SELECT s.shop_id, s.title,s.type,s.priority,s.hongbao,
            s.consumption, s.cover,s.images,s.province_id,s.city_id,s.district_id,
            s.phone,s.address, ss.score, ss.comment, ss.view, ss.sales, s.longitude,s.latitude,
            (ST_DISTANCE(POINT(s.longitude, s.latitude),POINT({$user_lng}, {$user_lat}))*{$distance_const}) AS distance
            FROM shops s
            LEFT JOIN shop_statistics ss ON s.shop_id=ss.shop_id
            {$join}
            WHERE s.status=1 AND s.verify_status=1 {$where}
            {$having}
            ORDER BY s.priority DESC {$order}
            LIMIT {$start},{$size}");
        $data['next_page'] = $request['page'] + 1;
        $data['page_size'] = $request['size'];
        return $this->after($data);
    }

    /**
     * 获取商家列表V2
     * @param Request $request
     * @param $cur_user_id
     * @return mixed
     */
    public function shopsV2(Request $request, $cur_user_id){
        $lng = floatval($request['lng']);
        $lat = floatval($request['lat']);
        $user_lng = floatval($request['user_lng']);
        $user_lat = floatval($request['user_lat']);
        $lng_radius = floatval($request['lng_radius']);
        $lat_radius = floatval($request['lat_radius']);

        $where = '';
        $having = '';
        $order = '';
        $join = '';
        if(!empty($request['keyword']) || $request['keyword'] === '0'){
            $where .= " AND INSTR(s.title, '".$request['keyword']."') ";
        }
        if(!empty($request['district_id'])){
            $where .= " AND s.district_id={$request['district_id']} ";
        }
        if(!empty($request['city_id'])){
            $where .= " AND s.city_id={$request['city_id']} ";
        }
        if(!empty($request['type']) && $request['type'] != 12){
            $where .= " AND s.type='{$request['type']}' ";
        }elseif($request['type'] == 12){
            $where .= " AND s.type IN (6, 7, 9, 11, 12) ";
        }
        if(!empty($request['user_city_id']) && empty($request['keyword'])){
            $priority = Shop::select('shop_id')->where('city_id', $request['user_city_id'])
                ->whereIn('priority', [2,3])
                ->get()
                ->toArray();
            if(!empty($priority)){
                $tmp = [];
                foreach($priority as $v){
                    $tmp[] = $v['shop_id'];
                }
                $priority = implode(',', $tmp);
                $where .= " OR s.shop_id IN ({$priority}) ";
            }
        }
        if(!empty($request['distance'])){
            $having = " HAVING distance <= {$request['distance']} ";
            if(!empty($priority)){
                $having .= " OR s.shop_id IN ({$priority}) ";
            }
        }
        switch($request['order']){//1-距离 2-评价 3-价格 4-智能 5-人气
            case 2:
                $order .= ' ,ss.score DESC, ss.comment DESC, distance ';
                break;
            case 3:
                $order .= ' ,s.consumption, distance ';
                break;
            case 4:
                $order .= ' ,distance,ss.score DESC,ss.view DESC ';
                break;
            case 5:
                $order .= ' ,ss.view DESC, distance ';
                break;
            default:
                $order .= ' ,distance ';
        }
        if(empty($request['district_id']) && empty($request['city_id'])
            && empty($request['fav']) && empty($request['keyword'])
            && empty($request['distance']) && !empty($request['lng'])
            && !empty($request['lat']) && !empty($request['lng_radius'])
            && !empty($request['lat_radius'])
        ){
            $up_left_lng = $lng+$lng_radius;
            $up_left_lat = $lat-$lat_radius;
            $up_right_lng = $lng+$lng_radius;
            $up_right_lat = $lat+$lat_radius;
            $down_right_lng = $lng-$lng_radius;
            $down_right_lat = $lat+$lat_radius;
            $down_left_lng = $lng-$lng_radius;
            $down_left_lat = $lat-$lat_radius;
            $having = " HAVING MBRContains(st_GeomFromText('POLYGON(($up_left_lng $up_left_lat,$up_right_lng $up_right_lat,$down_right_lng $down_right_lat,$down_left_lng $down_left_lat,$up_left_lng $up_left_lat))'), POINT(s.longitude, s.latitude)) ";
            if(!empty($priority)){
                $having .= " OR s.shop_id IN ({$priority}) ";
            }
        }

        if(!empty($request['fav'])){
            $join .= " RIGHT JOIN shop_fav sf ON sf.shop_id=s.shop_id AND sf.status=1 AND sf.user_id='{$cur_user_id}' ";
        }

        $distance_const = Constants::$DISTANCE_CONST;
        $start = ($request['page']-1) * $request['size'];
        $size = $request['size']+1;
        $data = [];
        $data['list'] = DB::select("SELECT s.shop_id, s.title,s.type,s.priority,s.hongbao,
            s.consumption, s.cover,s.images,s.province_id,s.city_id,s.district_id,
            s.phone,s.address, ss.score, ss.comment, ss.view, ss.sales, s.longitude,s.latitude,
            (ST_DISTANCE(POINT(s.longitude, s.latitude),POINT({$user_lng}, {$user_lat}))*{$distance_const}) AS distance
            FROM shops s
            LEFT JOIN shop_statistics ss ON s.shop_id=ss.shop_id
            {$join}
            WHERE s.status=1 AND s.verify_status=1 {$where}
            {$having}
            ORDER BY s.priority DESC {$order}
            LIMIT {$start},{$size}");
        $data['next_page'] = $request['page'] + 1;
        $data['page_size'] = $request['size'];
        return $this->after($data);
    }

    /**
     * 获取商家详细数据
     * @param $id
     * @param $cur_user_id
     * @return mixed
     */
    public function detail($id, $cur_user_id){
        $data = $this->selectRaw('shops.*,if(shop_fav.status,1,0) AS is_fav')
            ->with('content')
            ->with('statistic')
            ->with('services')
            ->withOnly('managers', ['id','user_id','shop_id','name','nickname','cover','mobile'], ['status'=>1,'display'=>1])
            ->leftJoin('shop_fav', function($join) use ($cur_user_id){
                $join->on('shop_fav.shop_id', '=', 'shops.shop_id')->where('shop_fav.user_id', $cur_user_id);
            })
            ->where('shops.status',1)
            ->where('shops.verify_status',1)
            ->where('shops.shop_id', $id)
            ->firstOrFail();
        return $this->after($data);
    }

    /**
     * 检查商家是否启用
     * @param $shop_id
     * @return bool
     */
    public function checkIfActive($shop_id){
        $shop = $this->where('shop_id', $shop_id)->where('status', 1)->where('verify_status', 1)->first();
        $owner = ShopManager::where("shop_id", $shop_id)->where('status', 1)->where('level', 2)->first();
        if($shop && $owner){
            return true;
        }
        return false;
    }

    /**
     * 关联shop_content
     * @return \Illuminate\Database\Eloquent\Relations\HasOne
     */
    public function content(){
        return $this->hasOne('App\Models\Shop\ShopContent', 'shop_id', 'shop_id');
    }

    /**
     * 关联shop_statistic
     * @return \Illuminate\Database\Eloquent\Relations\HasOne
     */
    public function statistic(){
        return $this->hasOne('App\Models\Shop\ShopStatistic', 'shop_id', 'shop_id');
    }

    /**
     * 关联服务
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function services(){
        return $this->hasMany('App\Models\Shop\ShopService', 'shop_id', 'shop_id');
    }

    /**
     * 关联经理
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function managers(){
        return $this->hasMany('App\Models\Shop\ShopManagerFullDetail', 'shop_id', 'shop_id');
    }

    /**
     * 关联优惠信息
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function coupons(){
        $time = time();
        return $this->hasMany('App\Models\Shop\ShopCoupon', 'shop_id', 'shop_id')
            ->where('status', 1)
            ->where('start_at', '<=', $time)
            ->where('end_at', '>=', $time);
    }
}
